package com.schuxl.observer.bike.observer;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringEscapeUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.schuxl.observer.bike.dataobject.Ad;
import com.schuxl.observer.bike.dataobject.WillhabenAd;
import com.schuxl.observer.bike.dataobject.schemaTypen.sites.Sites.Site;

public class WillhabenBikeObserver extends BikeObserver<WillhabenAd> {

	
	private static final String WILLHABEN_SITE = "http://www.willhaben.at";
	
	
	public WillhabenBikeObserver(Site site) {
		super(site);
	}

	
	
	
	
	@Override
	protected List<WillhabenAd> parseOverview(Document document) {
		List<WillhabenAd> currentList = new ArrayList<WillhabenAd>();
		WillhabenAd willhabenAd = null;
		
		Elements elements = document.select("#resultlist li");
		for(Element element : elements) {
			if(element.toString().contains("google"))
				continue;
			willhabenAd = new WillhabenAd();
			String title = element.select(".media-body a").text();
			//Dadurch werden Werbungen ausgeklammert
			if(title==null || title.length()<=0) 
				continue;
			willhabenAd.setTitle(title);
			willhabenAd.setLink(WILLHABEN_SITE+element.select("a").attr("href"));
			String imgSrc = element.select("a img").attr("src");
			willhabenAd.setImageLink(imgSrc);
			String yearAndMilage = element.select(".desc-left").text();
			willhabenAd.setYear(Integer.parseInt(yearAndMilage.substring(0,4).replaceAll("\\D+","")));
			int kmEndIndex =  yearAndMilage.indexOf("km")-1;
			willhabenAd.setKilometers(yearAndMilage.substring(5, kmEndIndex).replaceAll("\\D+",""));
			String price = element.select(".pull-right").text();
			if("".equals(price.replaceAll("\\D+",""))) { //Replace, da manchmal "Verkauft" drinnen steht und das ergibt dann auch keinen coolen Integer :-)
				willhabenAd.setPrice(0);
			}else {
				willhabenAd.setPrice(Integer.parseInt(price.replaceAll("\\D+","")));
			}
			
			String locationAndDealer = StringEscapeUtils.unescapeHtml(element.select("span.address-lg").html());
			int indexOfBr = locationAndDealer.indexOf("br />");
			willhabenAd.setDealer(locationAndDealer.substring(indexOfBr+6));
			willhabenAd.setLocation(locationAndDealer.substring(0, indexOfBr-2));
			
			currentList.add(willhabenAd);
		}
		return currentList;
	}





	@Override
	protected Ad parseDetailSite(Document document, Ad ad) {
		Elements elements = document.select(".dl-horizontal");
		for(Element element : elements) {
			String key = element.select("dt").text();
			String value = element.select("dd").text();
			if("Name".equals(key))
				ad.setSeller(value);
			else if("Telefon".equals(key))
				ad.setPhone(value);
		}
		ad.setDiscription(document.select(".description").text());
		return ad;
	}
			
				
	

	
	
	
	
	
	
	
	
	
	
	
	
	
}
